package com.boot.websocket;

import com.boot.bean.UserDo;
import com.boot.enums.ResultEnum;
import com.boot.service.UserService;
import com.fasterxml.jackson.databind.util.JSONPObject;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import sun.plugin.javascript.JSObject;

import javax.management.modelmbean.RequiredModelMBean;
import java.util.*;

@Slf4j
@Component
public class MessageHandler implements WebSocketHandler {
    @Autowired
    private UserService userService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static Map<Long,WebSocketSession> usermaps = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        log.info("加入成员id:{}", this.get(webSocketSession).getUserId());
        usermaps.put(this.get(webSocketSession).getUserId(),webSocketSession);
        webSocketSession.sendMessage(new TextMessage( "21"));
        String str ="{\"size\":2501,\"type\":\"\",\"count\":\""+usermaps.size()+"\"}" ;
        webSocketSession.sendMessage(new TextMessage( str));
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        String str = webSocketMessage.getPayload().toString();
        StringBuilder sb = new StringBuilder("SELECT * FROM SYS_USER  u where  u.ROOM_ID=(SELECT  su.ROOM_ID FROM SYS_USER su  where su.USER_ID=? )  and u.USER_ID != ?");
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sb.toString(), this.get(webSocketSession).getUserId(), this.get(webSocketSession).getUserId());
        List<WebSocketSession> list = new ArrayList<>();
        for (Map<String, Object> map:maps) {
            Long uId = Long.valueOf(map.get("USER_ID").toString());
            WebSocketSession session = usermaps.get(uId);
            if (session!=null){
                list.add(session);
            }
        }

        for ( WebSocketSession session:list  ) {
            str = str.replace("count-value",list.size()+1+"");
            session.sendMessage(new TextMessage( str));
        }


    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        usermaps.remove(this.get(webSocketSession).getUserId());
        this.removeRoom(webSocketSession);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        usermaps.remove(this.get(webSocketSession).getUserId());
        this.removeRoom(webSocketSession);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    private UserDo get(WebSocketSession webSocketSession){
        UserDo userDo = (UserDo) webSocketSession.getAttributes().get(ResultEnum.USERKEY.getMessage());
        return userDo;
    }
    private UserDo getSql(WebSocketSession webSocketSession){
        UserDo userDo = (UserDo) webSocketSession.getAttributes().get(ResultEnum.USERKEY.getMessage());
        return userDo;
    }

    private void removeRoom(WebSocketSession webSocketSession){
        UserDo userDo = this.get(webSocketSession);
        userDo.setRoomId(null);
        userService.save(userDo);
    }
}
